const WebSocket = require('ws');
const handleConnection = require('./handlers/connectionHandler.js');
const  log  = require('./utils/logger.js');

const server = new WebSocket.Server({ port: 8050 });

server.on('connection', (ws) => {
    log.info('New client connected');

    // 监听客户端消息
    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message);
            log.info(`received data ${data}`)
            // 根据消息类型处理信令
            switch (data.type) {
                case 'offer':
                case 'answer':
                case 'candidate':
                    // 广播信令消息给其他客户端
                    broadcast(ws, data);
                    break;
                default:
                    log.warn(`Unknown message type: ${data.type}`);
            }
        } catch (error) {
            log.error(`Error processing message: ${error.message}`);
        }
    });

    ws.on('close', () => {
        log.info('Client disconnected');
    });

    ws.on('error', (error) => {
        log.error(`WebSocket error: ${error.message}`);
    });
});

// 广播信令消息给其他客户端
function broadcast(sender, message) {
    server.clients.forEach((client) => {
        if (client !== sender && client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(message));
        }
    });
}

server.on('listening', () => {
    log.info('Server is listening on ws://localhost:8080');
});

server.on('error', (error) => {
    log.error(`Server error: ${error.message}`);
});